package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	manufacturer2 "hc_server/routers/response/manufacturerResponse"
)

// Manufacturer 对接的厂商
type Manufacturer struct {
	Model
	Name string `gorm:"comment:'名字'"`
}

// ManufacturerExistByID 通过id判断是否存在
func ManufacturerExistByID(id int) (bool, error) {
	var mer Merchant
	err := db.Select("id").Where("id = ?", id).First(&mer).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此厂商不存在: id:%d err:%v", id, err)
		return false, fmt.Errorf("此厂商不存在")
	}

	return mer.ID > 0, nil
}

// ManufacturerGetInfoByID 通过id获取详情
func ManufacturerGetInfoByID(id interface{}) (*manufacturer2.GetManufacturerInfoResponse, error) {
	res := new(manufacturer2.GetManufacturerInfoResponse)
	err := db.Model(&Manufacturer{}).Where("id = ?", id).Scan(&res).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此商户不存在: id:%d err:%v", id, err)
		return nil, fmt.Errorf("此商户不存在: id:%d err:%v", id, err)
	}
	if cast.ToInt(res.Id) == 0 {
		logrus.WithError(err).Errorf("此厂商不存在: id:%d err:%v", id, err)
		return nil, errors.New("此厂商不存在")
	}

	return res, nil
}

// ManufacturerGetInfoList 获取厂商列表
func ManufacturerGetInfoList(id interface{}) ([]*manufacturer2.GetManufacturerInfoResponse, error) {
	res := make([]*manufacturer2.GetManufacturerInfoResponse, 0)
	err := db.Model(&Manufacturer{}).Scan(&res).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此商户不存在: id:%d err:%v", id, err)
		return nil, fmt.Errorf("此商户不存在: id:%d err:%v", id, err)
	}

	return res, nil
}
